<template>
  <div class="common-list-view__v2" v-loading="loading">
    <div class="gante">
      <div class="add-btn" >
        <div class="left-btn">
            <el-dropdown v-if="btnAuth.createProjectAuth">
            <el-button type="primary" icon="el-icon-plus">{{$t('common.base.create')}}</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item, index) in projectTypeList" :key="index">
                <div @click="openProjectCreateTab(item.id)">{{ item.label }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div v-if="tableInit" class="el-dropdown cur-point acenter" @click="handleSelectColumn">
          <span >{{ $t('common.base.choiceCol') }} </span> 
          <i class="iconfont icon-fdn-select ml_4"></i>
        </div>
      </div>
    </div>
    <!-- 分页 S -->
    <div class="table-footer bbx-normal-table-footer-10">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ dataListPageInfo.total || 0 }}</span>
        </i18n>
      </div>
      <el-pagination
        background
        @current-change="handlePageNumChange"
        @size-change="handleSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="searchParams.pageSize"
        :current-page="searchParams.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="dataListPageInfo.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { useFetchProjectTableTimelineList,useFetchProjectAuthButton } from '@src/modules/projectManage/projectManageList/hooks/useFetch';
import { useOpenTab } from '@src/modules/projectManage/projectManageList/hooks/useOpenTab';
import { defaultTableData } from '@src/util/table'
/* model */
import { ViewTypeComponentNameEnum } from '@src/modules/projectManage/projectManageList/model';
/* vue */
import { ref, computed, onMounted, reactive, onUnmounted } from 'vue';
import { t } from '@src/locales';
import Vue from 'vue';

export default {
  name: ViewTypeComponentNameEnum.Time,
  props: {
    columns: {
      type: Array,
      default: [],
    },
    params: {
      type: Object,
      default: {},
    },
    packUp: {
      type: Boolean,
    },
    projectTypeList: {
      type: Array,
      default: []
    }
  },
  watch: {
    packUp() {
      this.$nextTick(() => {
        this.init();
      });
    },
    columns:{
      handler() {
        setTimeout(() => {
          if(!this.GANTT)return;
          this.init();
        }, 200);
      },
    },
  },
  setup(props, { emit }) {
    const { btnAuth, fetchProjectAuthButton } = useFetchProjectAuthButton();
    const { openProjectViewTab,openProjectCreateTab } = useOpenTab();
    const { loading, dataList, dataListPageInfo, fetchProjectTableTimelineList } = useFetchProjectTableTimelineList();
    // 搜索参数
    const searchParams = reactive({
      pageSize: 10,
      pageNum: 1,
      column: '',
      asc: null,
    });

    // 选择列
    const handleSelectColumn = () => {
      emit('handleSelectColumn');
    }

    const showColumns = computed(() => {
      return (props.columns || []).filter(item => item.show);
    });
    const ganttData = ref([]);
    // 搜索
    const search = isRefresh => {
      // 需要刷新
      if (isRefresh) return handlePageNumChange(1);

      const params = { ...searchParams, ...props.params };
      fetchProjectTableTimelineList(params).then(res => {
        ganttData.value = (dataList.value || []).map(item => {
          return {
            // ...item,
            params: {
              ...item,
              planStartTime: format(new Date(new Date(item.planStartTime).setHours(0, 0, 0, 0)), 1),
              planEndTime: format(new Date(new Date(item.planEndTime).setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1), 1),
              progress: item.projectProcess,
            },
            start_time: new Date(new Date(item.planStartTime).setHours(0, 0, 0, 0)).getTime(),
            end_time: new Date(new Date(item.planEndTime).setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1).getTime(),
          };
        });
        init();
      });
    };

    // 页码跳转
    const handlePageNumChange = pageNum => {
      searchParams.pageNum = pageNum;
      dataList.value = [];
      search();
    };

    // 分页条数改变
    const handleSizeChange = pageSize => {
      searchParams.pageSize = pageSize;
      searchParams.pageNum = 1;
      search();
    };

    // 甘特图
    const GANTT = ref(null);
    const tableInit = ref(false)
    const th_data = {
      projectName: {
        value: t('projectManage.setting.projectName'),
        width: 200,
        showToast: true,
        listen_click: true
      },
      progress: {
        value:  t('common.base.progress'),
        width: 140,
      },
      planStartTime: {
        value: t('common.form.type.planStartTime'),
        width: 120,
        showToast: true,
        chooseTime: true,
        time_mode: 1,
        sort_type: 'asc',
      },
      planEndTime: {
        value: t('common.form.type.planEndTime'),
        width: 120,
        showToast: true,
        chooseTime: true,
        time_mode: 2,
        sort_type: 'asc',
      },
      duration: {
        value: t('common.projectManage.gantt.duration'),
        width: 80,
        showToast: true,
        sort_type: 'asc',
      },
    };
    let fixed_th_data = {}
    const init = () => {
      fixed_th_data = {}
      let otherColumns = {};
      showColumns.value.forEach(item => {
        if(!['projectName','planStartTime','planEndTime','duration','progress'].includes(item.fieldName)){
          if(item.fieldName!=='projectNo'){
            otherColumns[item.fieldName] = {
              value: item.displayName,
              width: item.fieldName=='projectStatusName'?100:140,
              field:{
                fieldName: item.fieldName,
                formType: item.formType,
                ...item
              },
            };
          }else{
            //编号置顶
            fixed_th_data = {
              projectNo:{
                value: item.displayName,
                width: 140,
                field:{
                  fieldName:item.fieldName,
                  formType:item.formType
                },
                listen_click:true
              },
              ...th_data
            }
          }
        }
      });
      Vue.prototype
        .$gante({
          container: '.gante',
          ganteData: ganttData.value,
          start_time: new Date(new Date().setHours(0, 0, 0, 0)).getTime() - 550 * 24 * 3600000,
          end_time: new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1).getTime() + 550 * 24 * 3600000,
          tabe_width: '50%',
          open: true,
          openLoad: true,
          time_mode: 1,
          th_data: { ...fixed_th_data,...th_data, ...otherColumns },
          height: 'calc(100% - 100px)',
          onEdit(data) {
            console.log(data);
          },
          onClick(data) {
            if(data.argument == 'projectNo' || data.argument == 'projectName'){
              openProjectViewTab(data.data.params)
            }
          },
          onLoad(resolve) {
            resolve(false, [], new Date(new Date().setHours(0, 0, 0, 0)).getTime() - 550 * 24 * 3600000, new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1).getTime() + 550 * 24 * 3600000);
          },
          onDragChangeTime(data, resolve) {
            resolve(false);
          },
        })
        .then(data => {
          GANTT.value = data;
          // 页面初始化完之后展示该数据
          tableInit.value = true
        });
    };
    const format = (time, mode) => {
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();
      if (mode == 1) {
        return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
      } else if (mode == 2) {
        return year + '-' + (month < 10 ? '0' + month : month);
      } else if (mode == 3) {
        return day < 10 ? '0' + day : day;
      } else if (mode == 4) {
        return month < 10 ? '0' + month : month;
      } else if (mode == 5) {
        return year;
      }
    };
    onMounted(() => {
      fetchProjectAuthButton();
      search();
      window.addEventListener('resize', init,false)
    });
    onUnmounted(()=>{
      window.removeEventListener('resize', init)
    })
    return {
      defaultTableData,
      search,
      searchParams,
      loading,
      dataList,
      dataListPageInfo,
      handlePageNumChange,
      handleSizeChange,
      GANTT,
      ganttData,
      th_data,
      init,
      tableInit,
      btnAuth,
      openProjectCreateTab,
      handleSelectColumn,
    };
  },
};
</script>

<style lang="scss" scoped>
.gante {
  height: calc(100% - 50px);
  position:relative;
  .add-btn{
    position: absolute;
    top:0;
    height:40px;
    z-index: 10;
    margin-top: 4px;
    display: flex;
    justify-content: space-between;
    .left-btn {
      flex: 1;
    }

    // .acenter {
    //   position: absolute;
    //   right: 10px;
    //   top: 5px;
    // }
  }
}
</style>
